package org.MobileSales.Geolocalization;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.util.Log;

public class Geolocalization {
	
	public static Location getCurrentLocation(Context context){
		LocationManager locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
    	
		Criteria criteria = new Criteria();
		String bestprovider = locationManager.getBestProvider(criteria, false);
		Location location = locationManager.getLastKnownLocation(bestprovider);
    	
		if (location == null)
		{
			List<String> providers = locationManager.getAllProviders();
			for (String p : providers){
				location = locationManager.getLastKnownLocation(p);
				if (location != null)
					return location;
			}
		}
		return location;
	}

	public static Location reverseGeocode(Context context, String address){
        if (address == null || address == "") {
            return null;
        }

        int maxResults = 1;

        Geocoder gc = new Geocoder(context, Locale.getDefault());
        List<Address> addresses = new ArrayList<Address>();
		try {
			addresses = gc.getFromLocationName(address, maxResults);
		} catch (IOException e) {
			Log.d("Geolocalization.reverseGeocode", e.getMessage());
			return null;
		}

        if (addresses.size() == 1) {
        	Location loc = new Location("Geolocalization");
        	loc.setLatitude(addresses.get(0).getLatitude());
        	loc.setLongitude(addresses.get(0).getLongitude());
        	return loc;
        } else {
            return null;
        }
	}

	public static String geocode(Context context, Location location){
        if (location == null) {
            return null;
        }
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        int maxResults = 1;

        Geocoder gc = new Geocoder(context, Locale.getDefault());
        List<Address> addresses = new ArrayList<Address>();
		try {
			addresses = gc.getFromLocation(latitude, longitude, maxResults);
		} catch (IOException e) {
			Log.d("Geolocalization.geocode", e.getMessage());
			return null;
		}

        if (addresses.size() == 1) {
        	StringBuilder sb = new StringBuilder();
        	for (int i = 0; i < addresses.get(0).getMaxAddressLineIndex(); i++)
        		sb.append(addresses.get(0).getAddressLine(i)).append("\n");
        	return sb.toString();
        } else {
            return null;
        }
	}
}
